#!/usr/bin/python

import sys
import re
import os
from testUnit import tester

class iopWeb():

    global Excute
    Excute = os.system

    def __init__(self):
        return


    def config(self,ips,proxy,ssl,commonPass,encryptedPass):
        self.yaml(proxy)
        for ip in ips:
            Excute("ssh "+ip+" \"if [ ! -x /opt/tomcat-cloud-web ];then\n mkdir /opt/tomcat-cloud-web /opt/jdk\n fi\"")
            Excute("scp ./resource/cache/jdk/java.tar.gz root@"+ip+":/tmp")
            Excute("scp ./resource/cache/tomcat/tomcat.tar.gz root@"+ip+":/tmp")
            Excute("ssh "+ip+" tar zxf /tmp/java.tar.gz -C /opt/jdk")
            Excute("ssh "+ip+" tar zxf /tmp/tomcat.tar.gz -C /opt/tomcat-cloud-web")
            Excute("scp -r ./resource/web/cloud-web/  root@"+ip+":/opt/tomcat-cloud-web/webapps/")
            Excute("ssh "+ ip +" \"echo -e 'export JAVA_HOME=/opt/jdk\nexport PATH=$PATH:/opt/jdk/bin' >> /root/.bash_profile\"")
        self.configure(proxy,ips,ssl,encryptedPass)
        self.sql_import(ips,commonPass)
        protocol = "http"
        if ssl:
            protocol = "https"
        Excute("ssh "+ips[0]+" mysql -uroot -p"+commonPass+" << EOF\n use iop_dev;\nupdate am_endpoint set url='"+protocol+"://"+proxy+"/cloud-web/oss/v1/AUTH_%(tenant_id)s' where service_id='service_swift';\nupdate image_image SET copy_from = CONCAT('"+protocol+"://"+proxy+"/cloud-web/imageFiles/',id) WHERE virtual_env_type = 'OPENSTACK';\nEOF")
        return

    def yaml(self,proxy_ip):
        reader = open("./config/iop-web/cloud_config.yml","r")
        yaldata = reader.readlines()
        reader.close()
        writer = open("./resource/web/cloud-web/WEB-INF/classes/cloud_config.yml","w")
        for line in yaldata:
            line = line.replace('proxyip',proxy_ip)
            writer.write(line)
        writer.close()


    def configure(self,proxy_ip,ips,ssl,encryptedPass):
        if not os.path.exists("/tmp/iop/cloudweb"):
            Excute("mkdir -p /tmp/iop/cloudweb")
        Excute("rm -rf  /tmp/iop/cloudweb/*")
        reader = open("./config/iop-web/iop_config","r")
        config_data = reader.readlines()
        reader.close()
        for config in config_data:
            temp_data = config.split("!!!")
            filename = temp_data[0]
            temp_data = temp_data[1]
            temp = temp_data.split("&")
            flag = temp[1]
            temp_data = temp[0]
            temp = temp_data.split("$")
            atributes = temp
            self.set_conifg_file(filename,atributes,proxy_ip,ips,flag,ssl,encryptedPass)
            for ip in ips:
                Excute("scp /tmp/iop/cloudweb/"+filename+" root@"+ip+":/opt/tomcat-cloud-web/webapps/cloud-web/WEB-INF/classes/")
        return 
    
    def set_conifg_file(self,filename,atributes,proxy_ip,ips,flag,ssl,encryptedPass):
        if os.path.exists("/tmp/iop/cloudweb/"+filename):
            if os.path.exists("/tmp/iop/cloudweb/"+filename+".tmp"):
                Excute("rm -rf /tmp/iop/cloudweb/"+filename+".tmp")
            Excute("cp /tmp/iop/cloudweb/"+filename+" /tmp/iop/cloudweb/"+filename+".tmp")
            reader = open("/tmp/iop/cloudweb/"+filename+".tmp","r")
        else:
            reader = open("./resource/web/cloud-web/WEB-INF/classes/"+filename,"r")
        data = reader.readlines()
        reader.close()
        writer = open("/tmp/iop/cloudweb/"+filename,"w")
        j = 0
        for atribute in atributes:
                temp = atribute.split("=")
                for i in range(j,len(data)):
                    if re.search(temp[0],data[i]):
                        if flag == "proxy\n":
                            if ssl:
                                data[i] = re.sub("http","https",data[i])
                            writer.write(re.sub(r"\${proxy}(\n)?",proxy_ip,data[i])+"\n")
                            j = i+1
                            break
                        elif flag == "password\n":
                            writer.write(re.sub(r"\${password}(\n)?",encryptedPass,data[i])+"\n")
                            j = i+1
                            break
                        else:
                            value = ips[0]+":5672"
                            for x in range(1,len(ips)):
                                value += ","+ips[x]+":5672"
                            writer.write(re.sub(r"=.*$","="+value,data[i])+"\n")
                            j = i+1
                            break
                    else:
                        writer.write(data[i])
        if j != len(data)-1:
            for i in range(j,len(data)):
                 writer.write(data[i])
        return

   
    def sql_import(self,ips,commonPass):
        for ip in ips:
            Excute("scp ./config/iop-web/iop_dev.sql ./config/iop-web/iop_dev_monitor.sql root@"+ip+":/tmp")
            Excute("ssh "+ip+" \"mysql -p"+commonPass+" -e 'source /tmp/iop_dev_monitor.sql'\"")
            Excute("ssh "+ip+" \"mysql -p"+commonPass+" -e 'source /tmp/iop_dev.sql'\"")


    def run(self,ips):
        for ip in ips:
            Excute("ssh "+ip+" \"export PATH=\$PATH:/opt/jdk/bin;export JAVA_HOME=/opt/jdk;/opt/tomcat-cloud-web/bin/startup.sh\"")

    def stop(self,ips):
        for ip in ips:
            Excute("ssh "+ip+" export PATH=\$PATH:/opt/java/bin;/opt/tomcat-cloud-web/bin/stop.sh")
        return

if __name__ == "__main__":
    T = tester()
    if not T.test():
        raise Exception("less arguments or illegal arguments")
    ips = T.get_ips()
    O = iopWeb()
    O.config(ips,"10.110.17.136")
    O.sql_import(ips)

